package impl

import (
	"context"
	"encoding/json"

	"atomgit.com/openlinksaas/extension-proto-gen-go.git/extension_mail_api"
	"atomgit.com/openlinksaas/tencent-mail/config"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
	ses "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/ses/v20201002"
)

type ApiImpl struct {
	extension_mail_api.UnimplementedExtensionMailApiServer
	cfg *config.ServerConfig
}

func NewApiImpl(cfg *config.ServerConfig) (*ApiImpl, error) {
	return &ApiImpl{cfg: cfg}, nil
}

func (apiImpl *ApiImpl) SendRegMail(ctx context.Context, req *extension_mail_api.SendRegMailRequest) (*extension_mail_api.SendRegMailResponse, error) {
	cred := common.NewCredential(apiImpl.cfg.SecretId, apiImpl.cfg.SecretKey)
	templateId := apiImpl.cfg.RegMail.TemplateId
	templateData, err := json.Marshal(map[string]string{
		apiImpl.cfg.RegMail.AuthCodeKey: req.AuthCode,
	})
	if err != nil {
		return nil, err
	}
	err = apiImpl.sendMail(cred, apiImpl.cfg.Region, apiImpl.cfg.SendUser, req.MailAddr, apiImpl.cfg.RegMail.Title, &ses.Template{
		TemplateID:   &templateId,
		TemplateData: common.StringPtr(string(templateData)),
	})
	if err != nil {
		return nil, err
	}
	return &extension_mail_api.SendRegMailResponse{}, nil
}

func (apiImpl *ApiImpl) SendResetMail(ctx context.Context, req *extension_mail_api.SendResetMailRequest) (*extension_mail_api.SendResetMailResponse, error) {
	cred := common.NewCredential(apiImpl.cfg.SecretId, apiImpl.cfg.SecretKey)
	templateId := apiImpl.cfg.ResetMail.TemplateId
	templateData, err := json.Marshal(map[string]string{
		apiImpl.cfg.ResetMail.AuthCodeKey: req.AuthCode,
	})
	if err != nil {
		return nil, err
	}
	err = apiImpl.sendMail(cred, apiImpl.cfg.Region, apiImpl.cfg.SendUser, req.MailAddr, apiImpl.cfg.ResetMail.Title, &ses.Template{
		TemplateID:   &templateId,
		TemplateData: common.StringPtr(string(templateData)),
	})
	if err != nil {
		return nil, err
	}
	return &extension_mail_api.SendResetMailResponse{}, nil
}

func (apiImpl *ApiImpl) sendMail(cred common.CredentialIface, region, senderAddr, recvAddr, subject string, template *ses.Template) error {
	cpf := profile.NewClientProfile()
	cpf.HttpProfile.Endpoint = "ses.tencentcloudapi.com"
	c, err := ses.NewClient(cred, region, cpf)
	if err != nil {
		return err
	}
	triggerType := uint64(1)
	sendReq := ses.NewSendEmailRequest()
	sendReq.FromEmailAddress = common.StringPtr(senderAddr)
	sendReq.Destination = common.StringPtrs([]string{recvAddr})
	sendReq.Subject = common.StringPtr(subject)
	sendReq.Template = template
	sendReq.TriggerType = &triggerType

	_, err = c.SendEmail(sendReq)
	return err
}
